package com.myapp.ruyixing.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.myapp.ruyixing.R;

public class TitleBar extends LinearLayout {

	public TitleBar(Context context) {
		super(context);
		initView(context);
	}

	public TitleBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);

		TypedArray typeArray = context.obtainStyledAttributes(attrs,
				R.styleable.titleBar);
		int iconId = typeArray.getResourceId(R.styleable.titleBar_iconSrc, -1);
		setIconDrawable(iconId);
		int rightIconId = typeArray.getResourceId(
				R.styleable.titleBar_iconRightSrc, -1);
		setRightIconDrawable(rightIconId);
		String title = typeArray.getString(R.styleable.titleBar_title);
		setTitleText(title);
		typeArray.recycle();
	}

	private void initView(Context context) {
		View view = inflate(context, R.layout.title_bar, null);
		addView(view, new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
	}

	public void setIconDrawable(int iconId) {
		if (iconId != -1) {
			((ImageView) findViewById(R.id.img_icon)).setImageResource(iconId);
		} else {
			((ImageView) findViewById(R.id.img_icon)).setVisibility(View.GONE);
		}
	}

	public void setIconVisibility(boolean visible) {
		findViewById(R.id.img_icon).setVisibility(
				visible ? View.VISIBLE : View.INVISIBLE);
	}

	public void setRightIconDrawable(int iconId) {
		if (iconId != -1) {
			((ImageView) findViewById(R.id.img_icon_right))
					.setImageResource(iconId);
		}
	}

	public void setRightIconVisibility(boolean visible) {
		findViewById(R.id.img_icon_right).setVisibility(
				visible ? View.VISIBLE : View.INVISIBLE);
	}

	public ImageView getIconView() {
		return (ImageView) findViewById(R.id.img_icon);
	}

	public void setTitleText(String title) {
		if (!TextUtils.isEmpty(title)) {
			((TextView) findViewById(R.id.text_title)).setText(title);
		}
	}

	public void setOnIconClickedListener(OnClickListener listener) {
		findViewById(R.id.img_icon).setOnClickListener(listener);
	}

	public void setOnRightIconClickedListener(OnClickListener listener) {
		findViewById(R.id.img_icon_right).setOnClickListener(listener);
	}

	public void showLoading(boolean show) {
		if (show) {
			findViewById(R.id.loading).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.loading).setVisibility(View.GONE);
		}
	}

}
